﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hardanger.Model;

namespace Hardanger.Features
{
    public class TCPWebRequest
    {
        private String _raw;
        public string Raw
        {
            get
            {
                BuildRequest();
                return _raw;
            }
        }
        public HttpPost Post { get; set; }
        public Dictionary<string, string> Headers { get; set; }
        public String Method { get; set; }
        public String HttpVersion { get; set; }
        public Boolean SSL { get; set; }
        public Uri Uri { get; set; }
        public String Hostname { get; set; }
        public int Port { get; set; }

        private void BuildRequest()
        {
            StringBuilder httpRequest = new StringBuilder();
            httpRequest.Append(Method);
            httpRequest.Append(" ");
            httpRequest.Append(Uri);
            httpRequest.Append(" ");
            httpRequest.Append(HttpVersion);
            httpRequest.Append(Environment.NewLine);
            AddHeaders(httpRequest);
            httpRequest.Append(Environment.NewLine);
            if (Method == "POST")
            {
                AddBody(httpRequest);
                httpRequest.Append(Environment.NewLine);
            }
            _raw = httpRequest.ToString();
        }

        private void AddBody(StringBuilder httpRequest)
        {
            if (Post.Parameters.Count > 0)
            {
                foreach (var param in Post.Parameters)
                {
                    httpRequest.Append(param.Key);
                    if (!String.IsNullOrEmpty(param.Value))
                    {
                        httpRequest.Append("=");
                        httpRequest.Append(param.Value);
                    }
                    httpRequest.Append("&");
                }
                httpRequest.Remove(httpRequest.Length - 1, 1);
            }
        }

        private void AddHeaders(StringBuilder httpRequest)
        {
            foreach (var header in Headers)
            {
                httpRequest.Append(header.Key);
                httpRequest.Append(": ");
                httpRequest.Append(header.Value);
                httpRequest.Append(Environment.NewLine);
            }
        }      
    }
}
